#include "stdafx.h"
#include "sboxlayer.h"

static void MergeNibble( const unsigned char in_mergenibble[] , unsigned char out_mergenibble[] )
{
	for ( int i = 0 ; i <= 15 ; i++ )
	{
		out_mergenibble[i] = (in_mergenibble[4*i+3]<<3)|(in_mergenibble[4*i+2]<<2)|(in_mergenibble[4*i+1]<<1)|(in_mergenibble[4*i]) ;
	}
}

static void SplitNibble( const unsigned char in_splitnibble[] , unsigned char out_splitnibble[] )
{
	for ( int i = 0 ; i <=15 ; i++ )
	{
		out_splitnibble[4*i] = in_splitnibble[i] & 0x01 ;
		out_splitnibble[4*i+1] = (in_splitnibble[i] >> 1) & 0x01 ; 
		out_splitnibble[4*i+2] = (in_splitnibble[i] >> 2) & 0x01 ; 
		out_splitnibble[4*i+3] = (in_splitnibble[i] >> 3) & 0x01 ; 
		// 		for ( int j = 0 ; j <=3 ; j++ )
		// 		{
		// 			out_splitnibble[4*i+j] = (in_splitnibble[i] >> j) & 0x01 ;  
		// 		}
	}
}

void sBoxLayer( const unsigned char in_sbox[] , unsigned char out_sbox[] )
{
	unsigned char tmp_in_nibble[16] ;
	unsigned char tmp_out_nibble[16] ;
	const unsigned char sbox[16] = { 
		0x0c , 0x05 , 0x06 , 0x0b , 
		0x09 , 0x00 , 0x0a , 0x0d ,
		0x03 , 0x0e , 0x0f , 0x08 ,
		0x04 , 0x07 , 0x01 , 0x02  } ;
		MergeNibble( in_sbox , tmp_in_nibble ) ;
		for ( int i = 0 ; i <= 15 ; i++ )
		{
			tmp_out_nibble[i] = sbox[tmp_in_nibble[i]] ;
		}
		SplitNibble( tmp_out_nibble , out_sbox ) ;
}